import React, { Component } from 'react'
import GoBack from '@/components/TheGoBack'
import '../style/style.less'
import TheImage from '@/components/TheImage'
import { Descriptions, Button, Tabs } from 'antd'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheButton from '@/components/TheButton'
import { apiStoreInfoDetail, apiShopBillView, apiShopBillOrderPage, apiShopBillSettlement } from '@/request/financial'
import _ from 'lodash'

const { TabPane } = Tabs;

export default class MallDetails extends Component {
  state = {
    storeInformation: {},
    billInformation: {},
    tabData: [
      {
        label: '订单列表',
        value: 'S'
      },
      {
        label: '退单列表',
        value: 'R'
      }
    ],
    columnsS: [
      {
        title: '订单编号',
        dataIndex: 'orderCode',
        key: 'orderCode'
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "付款方式",
        dataIndex: "payWay",
        key: "payWay",
        render: (text, render) => {
          let label = ''
          switch (render.payWay) {
            case 'WeChat':
              label = '微信'
              break;
            case 'Alipay':
              label = '支付宝'
              break;
            case 'UnionPay':
              label = "银联"
              break;
            default:
              label = "未知支付方式"
          }
          return label;
        }
      },
      {
        title: "订单时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "完成时间",
        dataIndex: "finishTime",
        key: "finishTime",
      },
      {
        title: '补贴金额',
        dataIndex: 'mallSubsidiesMoney',
        key: 'mallSubsidiesMoney',
        render: (text, record) => {
          return <React.$Price price={record.mallSubsidiesMoney || 0} />
        }
      },
      {
        title: '应结金额',
        dataIndex: 'orderTotalScore',
        key: 'orderTotalScore',
        render: (text, record) => {
          return <React.$Price price={record.orderTotalScore || 0} />
        }
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <TheButton
            onClick={() => this.props.history.push(`/order/mallOrder/details/${record.orderId}`)}
          >详情</TheButton>
        }
      },
    ],
    columnsR: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "refundTime",
        key: "refundTime",
      },
      {
        title: "退单原因",
        dataIndex: "salesRemark",
        key: "salesRemark",
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <TheButton
            onClick={() => this.props.history.push(`/order/chargeback/mallDetails/${record.shopSalesReturnId}`)}
          >
            详情
          </TheButton>
        }
      },
    ],
    dataSourceS: [],
    dataSourceR: [],
    pageDataS: {
      pageNo: 1,
      pageSize: 10
    },
    pageDataR: {
      pageNo: 1,
      pageSize: 10
    },
    totalS: 0,
    totalR: 0,
    orderStatus: 'S'
  }
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    await this.getStoreData()
    await this.getBillData()
    await this.getOrderList()
  }
  getStoreData = async () => {
    const { storeId } = this.props.match.params
    let res = await apiStoreInfoDetail({ storeId })
    if (res.code === 0 && res.data) {
      let data = res.data
      this.setState({
        storeInformation: {
          storeName: data.storeName,
          address: data.addressMapLocation,
          image: data.storeShowFile,
          content: [
            {
              title: '联系人',
              value: data.storeContacts
            },
            {
              title: '联系方式',
              value: data.userMobile
            },
            {
              title: '服务项目',
              value: data.storeServiceNames
            },
            {
              title: '营业时间',
              value: `${data.storeOpenTime} ~ ${data.storeCloseTime}`
            },
            {
              title: '注册时间',
              value: data.createTime
            },
          ]
        },
      })
    }
  }
  getBillData = async () => {
    const { id } = this.props.match.params
    let res = await apiShopBillView({ id })
    if (res.code === 0 && res.data) {
      this.setState({
        billInformation: res.data
      })
    }
  }
  getOrderList = async () => {
    const { orderStatus } = this.state
    const { id } = this.props.match.params
    let res = await apiShopBillOrderPage({ orderStatus, ...this.state[`pageData${orderStatus}`], id })
    if (res.data && res.code === 0) {
      this.setState({
        [`pageData${orderStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${orderStatus}`]: res.totalCount,
        [`dataSource${orderStatus}`]: res.data
      })
    }
  }
  setTabKey = (orderStatus) => {
    this.setState({ orderStatus }, () => {
      this.getOrderList()
    })
  }
  confirm = id => {
    React.$confirm({
      title: '您确认对此账单进行结算操作吗？',
      onOk: async () => {
        let res = await apiShopBillSettlement({ id })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '操作成功'
          })
          this.getData()
        }
      }
    })
  }
  pageChange = (pageNo, pageSize, value) => {
    this.setState({
      [`pageData${value}`]: {
        pageNo,
        pageSize
      }
    }, () => this.getOrderList())
  }
  render() {
    const { storeInformation, tabData, loading, billInformation } = this.state
    return (
      <div className='financial-box'>
        <GoBack title="账单详情" history={this.props.history} />
        <div className="financial-content">
          {!_.isEmpty(storeInformation) && <div className='store-information'>
            <div className="store-image">
              <TheImage src={storeInformation.image} width={320} height={240} />
            </div>
            <div className="store-content">
              <div className='store-name'>{storeInformation.storeName}</div>
              <div className='content-item'>{storeInformation.address}</div>
              {
                storeInformation.content.map((v, i) => {
                  return <div className='content-item'>
                    <div>{v.title}：</div>
                    <div>{v.value}</div>
                  </div>
                })
              }
            </div>
          </div>}
          <div className='bill-information'>
            <div className='title'>账单明细</div>
            {!_.isEmpty(billInformation) && <Descriptions bordered column={1} labelStyle={{ textAlign: 'center' }} contentStyle={{ textAlign: 'center' }}>
              <Descriptions.Item label="结算单号">
                {billInformation.sn}
              </Descriptions.Item>

              <Descriptions.Item label="起止日期">
                {`${billInformation.startTime} ~ ${billInformation.endTime}`}
              </Descriptions.Item>

              <Descriptions.Item label="出账日期">
                {billInformation.createTime}
              </Descriptions.Item>

              <Descriptions.Item label="当前状态">
                {billInformation.billStatus === 'OUT' ? '待商家对账' : billInformation.billStatus === 'CHECK' ? '待平台出账' : '已完成'}
                {billInformation.billStatus === 'CHECK' && <Button style={{ marginLeft: 30 }} type="primary" size='small' onClick={() => this.confirm(billInformation.id)}>确认结算</Button>}
              </Descriptions.Item>

              <Descriptions.Item label="订单总金额">
                {<React.$Price price={billInformation.orderPrice} />}
              </Descriptions.Item>

              <Descriptions.Item label="应结总金额">
                {<React.$Price price={billInformation.billPrice} />}
              </Descriptions.Item>
            </Descriptions>}
          </div>
          <div className='order-information'>
            <div className='title'>账单明细</div>
            <Tabs
              onChange={(value) => this.setTabKey(value)}>
              {
                tabData.map((v, i) => {
                  return (
                    <TabPane tab={v.label} key={v.value}>
                      <div className="table-box">
                        <TheTable
                          scroll={{ x: "max-content", y: 600 }}
                          columns={this.state[`columns${v.value}`]}
                          dataSource={this.state[`dataSource${v.value}`]}
                          loading={loading}
                        />
                        <ThePagination
                          pageNo={this.state[`pageData${v.value}`].pageNo}
                          pageSize={this.state[`pageData${v.value}`].pageSize}
                          total={this.state[`total${v.value}`]}
                          pageChange={(pageNo, pageSize) =>
                            this.pageChange(pageNo, pageSize, v.value)
                          }
                        />
                      </div>
                    </TabPane>
                  );
                })
              }
            </Tabs>
          </div>
        </div>
      </div>
    )
  }
}
